package com.tcfvic.client.panels.widgets.widgetcontents;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.tcfvic.client.PersonService;
import com.tcfvic.client.PersonServiceAsync;
import com.tcfvic.client.panels.widgets.SimpleMessagePopup;
import com.tcfvic.client.panels.widgets.TCFWidgetContent;
import com.tcfvic.client.pojos.Employmentdetails;
import com.tcfvic.client.pojos.EmploymentdetailsId;
import com.tcfvic.client.pojos.Person;
import com.tcfvic.client.pojos.Workercompany;
import com.tcfvic.client.tools.Month;
import com.tcfvic.client.tools.Tools;

public class CompanyTab extends AbstractDataEntryWidgets implements
		TCFWidgetContent {

	private TextBox employeeNumber = new TextBox();
	private ListBox company = new ListBox();
//	private TextBox division = new TextBox();
	private TextBox position = new TextBox();
	private TextBox state = new TextBox();
	private ListBox status = new ListBox();
	private ListBox sector = new ListBox();
	private ListBox dayStart = null;
	private ListBox monthStart = null;
	private ListBox yearStart = null;
	private ListBox dayEnd = null;
	private ListBox monthEnd = null;
	private ListBox yearEnd = null;
	private TextBox yrsOfService = new TextBox();

	private final PersonServiceAsync personService = GWT
			.create(PersonService.class);

	public CompanyTab() {
		// initialise();
	}

	@Override
	public Widget getContent() {
		// Create a table to layout the form options
		FlexTable ft = new FlexTable();
		ft.setCellSpacing(4);
		ft.setWidth("100%");

		// Add some standard form options
		int row = 0;
		ft.setHTML(row, 0, "<b>Company</b>");
		ft.setWidget(row, 1, company);
		ft.setHTML(row, 2, "Employee no");
		ft.setWidget(row++, 3, employeeNumber);
		ft.setHTML(row, 0, "State");
		ft.setWidget(row, 1, state);
		ft.setHTML(row, 2, "Position");
		ft.setWidget(row++, 3, position);
//		ft.setHTML(row, 0, "Site");
//		ft.setWidget(row, 1, division);
		status = getStatus();
		ft.setHTML(row, 2, "Status");
		ft.setWidget(row++, 3, status);

		// DATE STARTED
		HorizontalPanel hp = new HorizontalPanel();
		dayStart = Tools.getDayListBox();
		monthStart = Tools.getMonthListBox();
		yearStart = Tools.getYearListBox();
		hp.add(dayStart);
		hp.add(monthStart);
		hp.add(yearStart);
		HTML label = new HTML("Start date");
		ft.setWidget(row, 0, label);
		ft.setWidget(row, 1, hp);

		// calculate years of service
		ft.setHTML(row, 2, "Years of service");
		yrsOfService.setEnabled(false);
		ft.setWidget(row++, 3, yrsOfService);

		// DATE FINISHED
		hp = new HorizontalPanel();
		dayEnd = Tools.getDayListBox();
		monthEnd = Tools.getMonthListBox();
		yearEnd = Tools.getYearListBox();
		hp.add(dayEnd);
		hp.add(monthEnd);
		hp.add(yearEnd);
		label = new HTML("<b>Finish date</b>");
		ft.setWidget(row, 0, label);
		ft.setWidget(row, 1, hp);

		// calculate years of service
		ft.setHTML(row, 2, "TCF Sector");
		yrsOfService.setEnabled(false);
		sector = getSector();
		ft.setWidget(row++, 3, sector);

		saveButton.getElement().setId("saveButton");
		ft.setWidget(row++, 0, saveButton);

		return ft;
	}

	private String getYearsOfService(Date start, Date end) {
		String yrsOfService = "";
		try {
			if (start != null && end != null) {
				Long diff = end.getTime() - start.getTime();
				diff = diff / 1000 / 60 / 60 / 24 / 365;
				NumberFormat nf = NumberFormat.getFormat("0.0");
				yrsOfService = nf.format(diff);
			}
		} catch (Exception e) {
		}
		return yrsOfService;
	}

	public static ListBox getStatus() {
		final ListBox dropBox = new ListBox(false);

		dropBox.addItem("");
		dropBox.addItem("Full time", "Full time");
		dropBox.addItem("Part time", "Part time");
		dropBox.addItem("Casual", "Casual");
		dropBox.addItem("Workcover", "Workcover");

		return dropBox;
	}

	public static ListBox getSector() {
		final ListBox dropBox = new ListBox(false);

		dropBox.addItem("");
		dropBox.addItem("Textile", "Textile");
		dropBox.addItem("Clothing", "Clothing");
		dropBox.addItem("Footwear", "Footwear");

		return dropBox;
	}

	@Override
	public void initialise() {
		company.clear();
		company.addItem("");
		personService.getAllCompanies(new AsyncCallback<List<Workercompany>>() {

			@Override
			public void onSuccess(List<Workercompany> result) {
				company.clear();
				company.addItem("");
				for (Workercompany wc : result) {
					company.addItem(wc.getName() + "-" + wc.getSite(), String
							.valueOf(wc.getId()));
				}
			}

			@Override
			public void onFailure(Throwable caught) {
				GWT.log("Could not retreive the companies list", caught);
				new SimpleMessagePopup(
						"Could not retreive the companies list: " + caught,
						null).showPopup();
			}
		});

	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T saveContent(T t) throws Exception {
		if (company.getSelectedIndex() > 0) {
			if (t != null && t instanceof Person) {
				Person person = (Person) t;
				Employmentdetails ed = new Employmentdetails();
				ed.setId(new EmploymentdetailsId(Integer.valueOf(company
						.getValue(company.getSelectedIndex())), 0));
				ed.setEmployeenumber(employeeNumber.getText());
//				ed.setDivision(division.getText());
				ed.setPosition(position.getText());
				ed.setState(state.getText());
				if (status.getSelectedIndex() >= 0) {
					ed.setStatus(status.getItemText(status.getSelectedIndex()));
				}
				if (sector.getSelectedIndex() >= 0) {
					ed.setSector(sector.getItemText(sector.getSelectedIndex()));
				}
				if (Tools.isValidDate(dayStart, monthStart, yearStart)) {
					ed.setDatestarted(Tools.parseDate(dayStart, monthStart,
							yearStart));
				}
				if (Tools.isValidDate(dayEnd, monthEnd, yearEnd)) {
					ed.setDateleaving(Tools
							.parseDate(dayEnd, monthEnd, yearEnd));
				}
				Set<Employmentdetails> edSet = new HashSet<Employmentdetails>();
				edSet.add(ed);
				person.setEmploymentdetailses(edSet);
				t = (T) person;
			}
		}
		return t;
	}
	
	@Override
	public void updateContent(Object o) {
		clear();
		if (o instanceof Person) {
			Person person = (Person) o;
			if (person.getEmploymentdetailses() != null) {
				for (Employmentdetails ed : person.getEmploymentdetailses()) {

					employeeNumber.setText(ed.getEmployeenumber());
					company.setSelectedIndex(getListIndexBasedOnId(company,
							String.valueOf(ed.getId().getWorkerCompanyId())));
//					division.setText(ed.getWorkercompany().getSite());
					position.setText(ed.getPosition());
					status.setSelectedIndex(Tools.getSelectedIndex(status, ed
							.getStatus()));
					sector.setSelectedIndex(Tools.getSelectedIndex(sector, ed
							.getSector()));
					state.setText(ed.getState());

					if (ed.getDatestarted() != null) {
						dayStart.setSelectedIndex(Tools.getSelectedIndexBasedOnItem(
								dayStart, Tools.getDay(ed.getDatestarted())));
						monthStart.setSelectedIndex(Month.valueOf(
								Tools.getMonth(ed.getDatestarted())
										.toUpperCase()).getId());
						yearStart.setSelectedIndex(Integer.parseInt(Tools
								.getYear(ed.getDatestarted())) - 1899);
					}
					if (ed.getDateleaving() != null) {
						dayEnd.setSelectedIndex(Tools.getSelectedIndexBasedOnItem(
								dayStart, Tools.getDay(ed.getDateleaving())));
						monthEnd.setSelectedIndex(Month.valueOf(
								Tools.getMonth(ed.getDateleaving())
										.toUpperCase()).getId());
						yearEnd.setSelectedIndex(Integer.parseInt(Tools
								.getYear(ed.getDateleaving())) - 1899);
					}

					yrsOfService.setText(getYearsOfService(ed.getDatestarted(),
							ed.getDateleaving()));

					// there should only be 1 in the list.
					break;
				}
			}
		}
	}

	@Override
	public void clear() {
		employeeNumber.setText("");
//		division.setText("");
		position.setText("");
		state.setText("");
		yrsOfService.setText("");
		Tools.resetList(company, dayStart, monthStart, yearStart, dayEnd,
				monthEnd, yearEnd, status, sector);
	}

	@Override
	public String getName() {
		return "Company";
	}

	@Override
	public void createNewRecord() {
		// TODO Auto-generated method stub

	}

}
